<script setup lang="ts">
import AudioVisualization from '@/components/AudioVisualization/index.vue'
import TransitionHeight from '@/components/TransitionHeight/index.vue'
import LinkIcon from '@/components/LinkIcon/index.vue'
import PullDown from '@/components/PullDown/index.vue'
import type { Props, Emits } from './utils/types'
import PurchaseMusicItem from './components/PurchaseMusicItem/index.vue'
import { useAuth } from '@/stores/index'

defineOptions({
    name: 'ItemMusic'
})

const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()

const $route = useRoute()

const $router = useRouter()

const goodsInfo = ref<any>({})
watch($props, (newValue) => {
    goodsInfo.value = newValue.item
}, { immediate: true })

provide('goodsInfo', goodsInfo)

function handleJumpMusicDetails(id: number) {
    window.open($router.resolve(`/music-details/${id}?categoryType=Music`).href, '_blank')
}

const isShowMusicDetail = shallowRef<boolean>(false)

function secondsToFormattedTime(seconds: number): string {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);

    // 格式化分钟和秒钟，确保总是两位数
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(remainingSeconds).padStart(2, '0');

    return `${formattedMinutes}:${formattedSeconds}`;
}

function onReady(value: number) {
    time.value = value
    timeText.value = secondsToFormattedTime(value)
}

const AudioVisualizationRef = shallowRef<any>()

const isPlay = shallowRef<boolean>(false)

const timeText = shallowRef<string>('00:00')
const time = shallowRef<any>()

let timer: any = null
const { isNextOperation } = useAuth()

watch(isPlay, (newValue) => {
    if (newValue) {
        AudioVisualizationRef.value?.play()
        startTime()
    } else {
        AudioVisualizationRef.value?.pause()
        endTime()
    }
})

function startTime() {
    timer = setInterval(() => {
        if (!AudioVisualizationRef.value) return
        const remainingTime = time.value - AudioVisualizationRef.value?.getCurrentTime()
        if (remainingTime >= 0) {
            timeText.value = secondsToFormattedTime(remainingTime)
        } else {
            isPlay.value = false
        }
    }, 500)
}

function endTime() {
    if (timer) {
        clearInterval(timer)
        timer = null
    }
}

function onFinish() {
    isPlay.value = false
}

const dialogVisible = shallowRef<boolean>(false)

function handleClickPurchase() {
    if (isNextOperation()) {
        dialogVisible.value = true
    }
}

function handlePlay() {
    $emit('on-play')
}

function onPlay() {
    isPlay.value = true
}

function handleSuspend() {
    isPlay.value = false
}

function handleJumpStore(item: any) {
    if (isNextOperation()) {
        window.open(`${import.meta.env.VITE_APP_CONSOLE_URL}/store-home?shopId=${item?.shop_id}`)
    }
}

defineExpose({
    onPlay,
    handleSuspend
})

</script>

<template>
    <div class="music-item">
        <div class="music-content">
            <div class="image-left" :style="{ backgroundImage: `url(${item.image})` }">
                <img class="play" src="./images/play.png" alt="play" v-show="!isPlay" @click="handlePlay">
                <img class="suspend" src="./images/suspend.png" alt="play" v-show="isPlay" @click="handleSuspend">
            </div>
            <div class="music-name">
                <div @click="handleJumpMusicDetails(item.id)">{{ item.title }}</div>
                <div>店家：<span @click="handleJumpStore(item)">{{ item?.user?.username }}</span></div>
            </div>
            <div class="player">
                <div class="time">{{ timeText }}</div>
                <AudioVisualization ref="AudioVisualizationRef" :src="item.sample" @onReady="onReady"
                    @onFinish="onFinish" />
            </div>
            <LinkIcon :item="item" @on-click-purchase="handleClickPurchase" />
            <div class="download">
                <button type="button" @click="handleClickPurchase">下&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;载</button>
            </div>
            <PullDown v-model="isShowMusicDetail" />
        </div>
        <TransitionHeight>
            <div class="music-detail" v-show="isShowMusicDetail">
                <div class="introduce">
                    <div>歌曲介绍</div>
                    <div>
                        {{ item?.brief }}
                    </div>
                </div>
                <div class="right">
                    <ul class="music-type">
                        <li>曲风：{{ item?.genre }}</li>
                        <li>情绪：{{ item?.emotion }}</li>
                        <li>乐器：{{ item?.musical }}</li>
                        <li>节拍：{{ item?.beat }}</li>
                    </ul>
                    <div class="keyword">
                        <div class="title">关键字：</div>
                        <div class="con" v-for="item in item?.key ? item?.key?.split('/') : []">{{ item }}</div>
                    </div>
                </div>
            </div>
        </TransitionHeight>
        <PurchaseMusicItem v-model="dialogVisible" />
    </div>
</template>


<style lang="scss" scoped>
.music-item {
    border-bottom: 1px solid #E8E8E8;
    font-family: 'SOURCEHANSANSCN-EXTRALIGHT';

    .music-detail {
        box-sizing: border-box;
        width: 100%;
        height: 170px;
        background-color: rgba(244, 245, 246, 1);
        margin-bottom: 17px;
        overflow: hidden;
        display: flex;

        .right {
            margin-left: 23px;

            .keyword {
                display: flex;
                margin-top: 20px;

                div {
                    width: 56px;
                    height: 20px;
                    color: rgba(16, 16, 16, 1);
                    font-size: 14px;
                }

                .con {
                    margin-right: 27px;
                }

                .title {
                    margin-right: 6px;
                }
            }

            .music-type {
                display: flex;
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
                list-style: none;
                margin-top: 25px;

                li {
                    margin-right: 48px;
                }
            }
        }

        .introduce {
            width: 300px;
            margin-left: 6px;

            div {
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
                margin-top: 17px;

                &:first-child {
                    margin-bottom: 14px;
                }
            }
        }
    }

    .music-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 0;

        .pull-down {
            margin-left: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all .2s;
        }

        .download {
            width: 200px;
            height: 36px;
            margin-left: 45px;

            button {
                width: 200px;
                height: 36px;
                line-height: 36px;
                border-radius: 21px;
                background-color: rgba(220, 221, 221, 1);
                color: #ffffff;
                font-size: 14px;
                border: none;
                text-align: center;
                transition: all .2s;
                cursor: pointer;

                &:hover {
                    background-color: #F91414;
                }
            }
        }

        .player {
            width: 414px;
            display: flex;
            align-items: center;
            margin-right: 30px;

            .time {
                margin-left: 10px;
                margin-right: 10px;
                color: rgba(16, 16, 16, 1);
                font-size: 14px;
            }
        }

        .music-name {
            margin-left: 23px;
            width: 205px;
            font-family: 'SOURCEHANSANSCN-LIGHT';

            div {
                margin: 10px 0;

                &:first-child {
                    color: rgba(16, 16, 16, 1);
                    font-size: 18px;
                    cursor: pointer;
                }

                &:last-child {
                    color: rgba(16, 16, 16, 1);
                    font-size: 14px;

                    span {
                        color: rgba(55, 133, 242, 1);
                        font-size: 14px;
                        cursor: pointer;
                    }
                }
            }
        }

        .image-left {
            width: 85px;
            height: 85px;
            background-color: #E8E8E8;
            border-radius: 50%;
            overflow: hidden;
            background-size: cover;
            background-position: center;
            display: flex;
            align-items: center;
            justify-content: center;

            .suspend {
                width: 35px;
                height: 35px;
                display: block;
                cursor: pointer;
            }

            .play {
                width: 30px;
                height: 30px;
                display: block;
                margin-left: 6px;
                cursor: pointer;
            }
        }
    }

}
</style>